package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"self-test/cache"
	"self-test/models"
	"self-test/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不可为空",
		})
		return
	}

	var user models.User

	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码三次错误，禁止登录",
		})
		return
	}

	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不存在此用户",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码三次错误，禁止登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
}

func RoleNode(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN role_nodes ON roles.id = role_nodes.rid
		  WHERE role_nodes.rid = 1
	*/

	var role []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN role_nodes ON roles.id = role_nodes.rid").
		Where("role_nodes.rid = ?", rid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
}

func UserRole(c *gin.Context) {
	uid := c.Query("uid")

	/*
		SELECT
		  *
		FROM
		  users
		  LEFT JOIN user_roles ON users.id = user_roles.uid
		  WHERE user_roles.uid = 1
	*/

	var user []models.User
	models.DB.Table("users").
		Joins("LEFT JOIN user_roles ON users.id = user_roles.uid").
		Where("user_roles.uid = ?", uid).
		Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})

}

func Add(c *gin.Context) {
	carTo := c.PostForm("car_to")
	carName := c.PostForm("car_name")
	carPrice := c.PostForm("car_price")
	data := models.Car{
		CarTo:    carTo,
		CarName:  carName,
		CarPrice: carPrice,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func CarOrder(c *gin.Context) {
	cid := c.Query("cid")

	var car []models.Car
	models.DB.Table("cars").
		Joins("LEFT JOIN car_orders ON cars.id = car_orders.cid").
		Where("car_orders.cid = ?", cid).
		Find(&car)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": car,
	})
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "4"))
	offset := (page - 1) * size
	var count int64
	var carOrderList []models.CarOrderList
	models.DB.Model(&carOrderList).Count(&count)

	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.
			Table("cars").
			Select(
				"car_orders.id as OrderId",
				"cars.car_to as CarTo",
				"cars.car_name as CarName",
				"cars.car_price as CarPrice",
				"car_orders.order_to as OrderTo",
				"car_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN car_orders ON cars.id = car_orders.cid").
			Offset(offset).Limit(size).Debug().Find(&carOrderList)
		jsonData, _ := json.Marshal(carOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carOrderList)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"car":   carOrderList,
			"count": count,
		},
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var carOrderList models.CarOrderList

	redis_key := "list_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.
			Table("cars").
			Select(
				"car_orders.id as OrderId",
				"cars.car_to as CarTo",
				"cars.car_name as CarName",
				"cars.car_price as CarPrice",
				"car_orders.order_to as OrderTo",
				"car_orders.order_price as OrderPrice",
			).
			Joins("LEFT JOIN car_orders ON cars.id = car_orders.cid").
			Where("car_orders.id =?", id).
			Debug().First(&carOrderList)
		jsonData, _ := json.Marshal(carOrderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carOrderList)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"car": carOrderList,
		},
	})
}
